//
//  GoodStorysDetailViewController.m
//  NBTripe
//
//  Created by Lee on 16/1/11.
//  Copyright © 2016年 Vicki. All rights reserved.
//

#import "GoodStorysDetailViewController.h"
#import "GoodStoryDetailModel.h"
#import "GoodStorysDetailTableViewCell.h"
@interface GoodStorysDetailViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableview;

@property (nonatomic, copy) NSString * introduction;

@property (nonatomic, strong) NSMutableArray *storysArray;
//头视图
@property (nonatomic, strong) UIImageView *backgroundview;
//自适应高度
@property (nonatomic, assign)  CGRect rect;
//weburl
@property (nonatomic, copy) NSString * url;

@end

@implementation GoodStorysDetailViewController

static CGFloat kImageOriginHight = 200;

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self getData];
    [self createTableVIew];
    // Do any additional setup after loading the view.
}
/**
 *  获取详细故事数据
 */
- (void)getData {
    self.storysArray = [[NSMutableArray alloc] initWithCapacity:0];
    NSString *spotId = _spotId.stringValue;
    [XYNetWorkTool getWithUrl:kGoodStoyURL(spotId) parameter:nil httpHeader:nil responseType:ResponseTypeJSON success:^(id result) {
        NSDictionary *dic = [[result objectForKey:@"data"] objectForKey:@"spot"];
        //获取简介
        _introduction = [dic objectForKey:@"text"];
        //获取weburl
        _url = [[dic objectForKey:@"target"] objectForKey:@"url"];
        //获取详细信息的数组
        NSArray *array = [dic objectForKey:@"detail_list"];
        for (NSDictionary *dic in array) {
            GoodStoryDetailModel *model = [[GoodStoryDetailModel alloc] initWithDataSource:dic];
            [self.storysArray addObject:model];
        }
        //刷新视图
        [self.tableview reloadData];
    } fail:nil];
}
/**
 *  创建tableview
 */
- (void)createTableVIew {
    self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HIGHT-95*XHIGHT) style:UITableViewStylePlain];
    _tableview.dataSource = self;
    _tableview.delegate = self;
    //_tableview.backgroundColor = [UIColor yellowColor];
    [_tableview registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewcell"];
    [_tableview registerClass:[GoodStorysDetailTableViewCell class] forCellReuseIdentifier:@"GoodStorysDetailTableViewCell"];
    self.automaticallyAdjustsScrollViewInsets = NO;
     _tableview.contentInset=UIEdgeInsetsMake(kImageOriginHight,0,0,0);
    //取消cell分割线
    self.tableview.separatorStyle =  UITableViewCellSeparatorStyleNone;
    self.tableview.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.tableview];
    [self createTopView];
}
/**
 *  创建头视图
 */
- (void)createTopView {
    //背景图
    self.backgroundview = [[UIImageView alloc] initWithFrame:CGRectMake(0, -kImageOriginHight, WIDTH, 230*XHIGHT)];
    [_backgroundview
     sd_setImageWithURL:[NSURL URLWithString:self.usermodel.cover] placeholderImage:[UIImage imageNamed:@"160.jpg"]];
    _backgroundview.userInteractionEnabled = YES;
    //背景效果图
    UIImageView *imageview = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, self.backgroundview.height)];
    imageview.tag = 1002;
    imageview.backgroundColor = [UIColor blackColor];
    imageview.alpha = 0.5;
    [_backgroundview addSubview:imageview];
    [self.tableview addSubview:self.backgroundview];
    //点击手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didPressHeadView)];
    [self.backgroundview addGestureRecognizer:tap];
    //头像
    UIImageView *touxiang = [[UIImageView alloc] initWithFrame:CGRectZero];
    [Convenience createCirCleImageView:touxiang WithFrame:CGRectMake(150*XWIDTH, 120*XHIGHT, 50*XWIDTH, 50*XWIDTH)WithCorNerRadius:25*XWIDTH];
    [touxiang sd_setImageWithURL:[NSURL URLWithString:_usermodel.avatar_m]placeholderImage:[UIImage imageNamed:@"160.jpg"]];
    [_backgroundview addSubview:touxiang];
    //作者
    UILabel *namelabel = [[UILabel alloc] initWithFrame:CGRectZero];
   [Convenience createLabel:namelabel WithFrame:CGRectMake(touxiang.origin.x-40, 170*XHIGHT, 130*XWIDTH, 30*XHIGHT) FrameWithTextColor:[UIColor whiteColor] TextColorWithFont:[UIFont boldSystemFontOfSize:17] FontWithNSTextAlignment:NSTextAlignmentCenter TextAlignmentWithNumberOfLines:0 WithText:_usermodel.name];
    
    [_backgroundview addSubview:namelabel];

}

/**
 *  tableview协议
 */
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
 
    return _storysArray.count+1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        return 30*XHIGHT;
    }
    else if (indexPath.row == 1) {
        self.rect = [_introduction boundingRectWithSize:CGSizeMake(WIDTH-20, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]} context:nil];
        return self.rect.size.height+10;
    }
    else {
        NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:12]};
        GoodStoryDetailModel *model = self.storysArray[indexPath.row-2];
        CGRect rect = [model.text boundingRectWithSize:CGSizeMake(WIDTH-20, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
       // NSLog(@"%d", (int)rect.size.height);
        return rect.size.height+250*XHIGHT;
    }
  
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 0) {
         UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewcell"];
        return cell;
    }
  
    if (indexPath.row == 1) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewcell"];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        cell.textLabel.text = _introduction;
        cell.textLabel.numberOfLines = 0;
        return cell;
    }
    else {
        GoodStorysDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GoodStorysDetailTableViewCell"];
        cell.detailmodel = _storysArray[indexPath.row-2];
        return cell;
    }
    
}
#pragma mark -- 滚动视图的代理方法
- (void)scrollViewDidScroll:(UIScrollView*)scrollView{
    /**
     *  关键处理：通过滚动视图获取到滚动偏移量从而去改变图片的变化
     */
    //获取滚动视图y值的偏移量
    UIImageView *backimageview = [self.view viewWithTag:1002];
    CGFloat yOffset  = scrollView.contentOffset.y;
   // NSLog(@"yOffset===%f",yOffset);
    CGFloat xOffset = (yOffset +kImageOriginHight);//?
    
    if(yOffset < -200*XHIGHT) {
        CGRect f = self.backgroundview.frame;
        f.origin.y= yOffset;
        f.size.height=  -yOffset;
        f.origin.x= xOffset;
        //int abs(int i); // 处理int类型的取绝对值
        //double fabs(double i); //处理double类型的取绝对值
        //float fabsf(float i); //处理float类型的取绝对值
        f.size.width=WIDTH + fabs(xOffset)*2;//?
        self.backgroundview.frame= f;
        backimageview.frame = f;
    }
}
/**
 *  头视图点击
 */
- (void)didPressHeadView {
    WebViewController *webVC = [[WebViewController alloc] init];
    [webVC WebUrl:_url];
    if(_url.length > 0)
    [self.navigationController pushViewController:webVC animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
